import Vue from 'vue'
import VueRouter from 'vue-router'
import { Dialog } from 'vant'
import store from '@/store/index.js'

Vue.use(VueRouter)

const Login= () => import( '@/views/login/index.vue')
const Home= () => import( '@/views/home/index.vue')
const Reply= () => import( '@/views/reply/index.vue')
const VideoDesc= () => import( '@/views/videoDesc/index.vue')
const My= () => import( '@/views/my/index.vue')
const Layout= () => import( '@/views/layout/index.vue')
const Search=()=>import('@/views/search/index.vue')
const Article=()=>import('@/views/article/index.vue')
const UserProfile=()=>import('@/views/user-profile/index.vue')
const UserChat=()=>import('@/views/user-chat/index.vue')
const routes = [
  {
    path:'/login',
    name:'login',
    component:Login,
    meta: { requiresAuth: false }
  },
  {
    path:'/',
    component:Layout,
    children:[
      {
        path:'',
        name:'home',
        component:Home,
        meta: { requiresAuth: false }
      },
      {
          path:'/reply',
          name:'reply',
          component:Reply,
          meta: { requiresAuth: false }
      },
      {
          path:'/video',
          name:'video',
          component:VideoDesc,
          meta: { requiresAuth: false }
      },
      {
          path:'/my',
          name:'my',
          component:My,
          meta: { requiresAuth: false }
      }
    ]
  },
  {
    path:'/search',
    name:'search',
    component:Search,
    meta: { requiresAuth: false }
  },
  {
    path:'/article/:articleId',
    name:'article',
    component:Article,
    //将动态路由参数映射到组件的props中，无论是访问还是维护性都很方便
    props:true,
    meta: { requiresAuth: false }
  },
  {
    path:'/user-profile',
    name:'user-profile',
    component:UserProfile,
    meta: { requiresAuth: false }
  },
  {
     path:'/user-chat',
     name:'user-chat',
     component:UserChat,
     meta: { requiresAuth: true }
  }
]




const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    //校验登录状态
    //如果已登录则直接通过
    if(store.state.user){
      return next()
    }
    //如果没有登录提示是否登录
    Dialog.confirm({
      title:'访问提示',
      message:'需要登录才能访问',
    }).then(()=>{
      // next({
      //   path: '/login',
      //   query: { redirect: to.fullPath }
      // })
      router.replace({
        //path: '/login',
        name:'login',
        query: { redirect:router.currentRoute.fullPath }
      })
    }).catch(()=>{
      //取消停止路由导航 中断
      next(false)
    })
  } else {
    //不需要登录状态的页面直接过去
    next() // 确保一定要调用 next()
  }
})
export default router
